/*
 * File Name :  WorkItemModel
 */
import BaseModel from 'base/models/BaseModel.js';
import DuplicableMixin from 'base/models/DuplicableMixin.js';
import Validation from 'backbone-validation'
import Radio from 'backbone.radio';
import {
    bindModelValidation,
    unbindModelValidation
} from 'backbone-tools';
import {
    strToFloat,
    getTvaPart
} from 'math.js';
import {
    findCurrentSelected
} from 'tools.js';


const WorkItemModel = BaseModel.extend(DuplicableMixin).extend(Validation.mixin).extend({
    props: [
        "id",
        "type_",
        "label",
        "description",
        "ht",
        "supplier_ht",
        "work_unit_quantity",
        "total_quantity",
        'quantity_inherited',
        "unity",
        "work_unit_ht",
        "total_ht",
        "sync_catalog",
        'price_study_work_id',
        'mode',
        'order',
    ],
    inherited_props: ['margin_rate'],
    defaults() {
        let config = Radio.channel('config');
        let defaults = config.request('get:options', 'defaults');
        return {
            work_unit_quantity: 1,
            quantity_inherited: true,
            margin_rate_editable: true,
            mode: 'supplier_ht'
        }
    },
    validation: {
        description: {
            required: true,
            msg: "Veuillez saisir une description"
        },
        work_unit_quantity: {
            required: function (value, attr, computedState) {
                if (!this.get('locked')) {
                    return true;
                }
            }
        },
        // unity: {
        //     required: true,
        //     msg: "Veuillez saisir une unité"
        // },
        ht: {
            required(value, attr, computedState) {
                return this.get('mode') == 'ht';
            },
            pattern: "amount",
            msg: "Veuillez saisir un coût unitaire, dans la limite de 5 chiffres après la virgule",
        },
        supplier_ht: {
            required(value, attr, computedState) {
                return this.get('mode') == 'supplier_ht';
            },
            pattern: "amount",
            msg: "Veuillez saisir un coût d'achat, dans la limite de 5 chiffres après la virgule",
        },
    },
    initialize: function () {
        BaseModel.__super__.initialize.apply(this, arguments);
        this.facade = Radio.channel('priceStudyFacade');
        this.config = Radio.channel('config');
        this.user_prefs = Radio.channel('user_preferences');
    },
    ht() {
        /* Return the ht value of this entry */
        return strToFloat(this.get('total_ht'));
    },
    validateModel() {
        bindModelValidation(this);
        const result = this.validate();
        unbindModelValidation(this);
        return result;
    },
});
export default WorkItemModel;